package com.chen.config.auth;

import feign.RequestInterceptor;
import feign.RequestTemplate;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Configuration;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.http.HttpHeaders;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

/**
 * @Author: chen
 * @Date: 2021/4/29 2:39 PM
 * @Version 1.0
 */
@Configuration
public class OAuth2FeignConfig implements RequestInterceptor {

    private static final String client_credentials = "client_credentials";

//    @Resource
//    private OAuth2FeignClient oAuth2FeignClient;
//
//    @Value("${user.basicToken:Basic aW5zaWRlLWFwcDppbnNpZGUtc2VjcmV0}")
//    private String basicToken;

    @Autowired
    private RedisTemplate<String,String> redisTemplate;

    @Override
    public void apply(RequestTemplate requestTemplate) {
        //从上线文中获取token
        ServletRequestAttributes requestAttributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
        String header = requestAttributes.getRequest().getHeader(HttpHeaders.AUTHORIZATION);
        if(StringUtils.isBlank(header)){
            String token = redisTemplate.opsForValue().get(client_credentials);
            if(token != null){
                header = token;
            }else {
                header = "bearer eyJhbGciOiJSUzI1NiIsInR5cCI6IkpXVCJ9.eyJzY29wZSI6WyJhbGwiXSwiZXhwIjoxNjIyMDE3MzU5LCJqdGkiOiI0NmYxNzYwMS0wYmJlLTQ2OTktOTQyNi1mZWVhMzNkOTdmNDgiLCJjbGllbnRfaWQiOiJpbnNpZGUtYXBwIn0.nNpvg7Zq_7QEX-OyakvelIt_v7O7-W1wQMFUDMmKZEbheANqvFs3v0eUnt6kMpUKoc6nmoxKvFkQ2YcoxslnZelU_WQYvoZnHI0bJZRQUoqcDc3mjiaPDv4pLJMi-gNAi-6AD2sBtHnqlgM-eIpCVaaqHR0IF1gpnuTwG2gBeKcsMwwHtWS4ZNvhlqwATvnt_nI7u4WggJ0dHzNLg11MnB1cZmdgVKmydZa8IdfxBqa3f8K88iCBExIwKpsPK0-YrQa4ZNRg6oJ4AV6CXri7UzbOgQS7XoNk2q4tnpReAafbeuAUjqIhY8TujrLZwt1nSNuySzAbtOtnQWntgfMhBg";
            }
        }
        requestTemplate.header(HttpHeaders.AUTHORIZATION, header);
    }

}
